package com.yangsen.register;

import com.jfinal.aop.Duang;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Redis;
import com.yangsen.Md5SaltTool.Md5SaltTool;
import com.yangsen.common.model.User;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

public class RegisterService {
    public static final RegisterService me = Duang.duang(RegisterService.class);
    private static final User userDao = new User().dao();

    public Ret check(String username) {
        User user = userDao.findFirst(userDao.getSqlPara("user.findByUsername", username));
        return Ret.by("status", null != user);
    }


    public Ret register(String username, String pwd, String nickname) {
        User isExists = userDao.findFirst(userDao.getSqlPara("user.findByUsername", username));
        if (null != isExists) {
            return Ret.by("status", false).set("msg", "用户已存在");
        }
        User user = new User();
        try {
            if (!nickname.isEmpty()) {
                if (user.setUsername(username).setPwd(Md5SaltTool.getEncryptedPwd(pwd)).setNickname(nickname).save()) {
                    String token = StrKit.getRandomUUID();
                    Redis.use().set(token, user);
                    return Ret.by("status", true).set("token", token);
                } else {
                    return Ret.by("status", false).set("msg", "未知错误");
                }
            } else {
                if (user.setUsername(username).setPwd(Md5SaltTool.getEncryptedPwd(pwd)).save()) {
                    String token = StrKit.getRandomUUID();
                    Redis.use().set(token, user);
                    return Ret.by("status", true).set("token", token);
                } else {
                    return Ret.by("status", false).set("msg", "未知错误");
                }
            }

        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return Ret.by("status", false).set("msg", "未知错误");
    }
}
